package com.codeZ.SingletonPattern.destroySingleton;

import java.lang.reflect.Constructor;

/**
 * @Author code_zhang
 * @Date 2024/6/15 17:42
 * 反射破坏单例模式
 */
public class ReflectDestroySingleton {


    public static void main(String[] args) throws Exception {
        //反射中，获取一个类或者调用某个类的方法，首先要获取到 该类的Class 对象
        Class<SingletonPattern01> singletonPattern01Class = SingletonPattern01.class;
        // getDeclaredXxx: 不受权限控制的获取类的成员
        Constructor<SingletonPattern01> constructor = singletonPattern01Class.getDeclaredConstructor();
        // 设置为true,就可以对类中的私有成员进行操作了
        constructor.setAccessible(true);
        SingletonPattern01 instance = constructor.newInstance();
        System.out.println(instance);
    }

}

class SingletonPattern01 {
    private SingletonPattern01() {
        // 解决办法
//        if (instance != null) {
//            throw new RuntimeException("单例模式不允许多个实例");
//        }
    }

    private static SingletonPattern01 instance = new SingletonPattern01();

    public static SingletonPattern01 getInstance() {
        return instance;
    }

}
